/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.dfs.interceptor;

import java.lang.reflect.Method;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;

import cn.waleychain.exchange.core.logger.LoggerHelper;


@Aspect
@Component
@Order(5)
public class RecordApiSpendTimeAspect {

	private static final Logger mLog = LoggerFactory.getLogger(RecordApiSpendTimeAspect.class);
	
	ThreadLocal<Long> startTime = new ThreadLocal<>();
	
	private Method method;
	
	@Pointcut("execution(public * cn.sstech.microservice.provider.user..*.*(..))")  
    public void controllerAspect() {  
	}  
	
	@Before("controllerAspect()")
	public void beforeHandler (JoinPoint joinPoint) {
		
		this.setMethod(joinPoint);
		
		startTime.set(System.currentTimeMillis());
		
		LoggerHelper.printLogDebug(mLog, logger(joinPoint));
	}

	@AfterReturning("controllerAspect()")
	public void afterHandler (JoinPoint joinPoint) {
		
		// 接收到请求，记录请求内容  
		try {
			if (method.getAnnotation(RequestMapping.class) == null) {
	        	return;
	        }
	        
	        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder  
	                .getRequestAttributes()).getRequest();
	        
			LoggerHelper.printLogInfo(mLog, null, "(" + request.getServletPath() + ")" + " >> IP：" + request.getRemoteAddr() + " SPEND TIME：" + (System.currentTimeMillis() - startTime.get()) + " ms");
		} catch (Exception e) {
			LoggerHelper.printLogErrorNotThrows(mLog, e, "记录日志");
		}

	}
	
	@AfterThrowing(value="controllerAspect()", throwing = "e")  
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
		
	}
	
	@AfterReturning(returning = "ret", pointcut = "controllerAspect()")  
    public void doAfterReturning(Object ret) throws Throwable {
		if (ret == null) {
			return;
		}
		
		LoggerHelper.printLogDebug(mLog, "请求返回：" + JSONObject.toJSONString(ret));
			
    }  

	private void setMethod(JoinPoint joinPoint) {
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();  
		method = methodSignature.getMethod();
	}
	
	@SuppressWarnings("rawtypes")
	private String logger(JoinPoint joinPoint) {
		
		if (method.getAnnotation(RequestMapping.class) == null) {
        	return "";
        }
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder  
                .getRequestAttributes()).getRequest();
		
		StringBuffer log = new StringBuffer();
		log.append("(" + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ")");
		log.append(" 参数：{");
		Enumeration map = request.getParameterNames();
		int n = 0;
		while (map.hasMoreElements()) {
			String obj = (String) map.nextElement();
			String value = request.getParameter(obj);
			
			if (n != 0) {
				log.append(", ");
			}
			
			log.append(obj);
			log.append("：");
			log.append(value);
			
			n++;
		}
		log.append("}");
		
		return log.toString();
	}
}
